const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

/**
 * 处理文件上传
 * @param {Object} file 上传的文件对象
 * @returns {Promise<Object>} 上传结果
 */
const uploadFile = async (file) => {
    try {
        // 生成唯一文件名
        const ext = path.extname(file.name);
        const fileName = `${uuidv4()}${ext}`;
        const filePath = path.join(uploadDir, fileName);

        // 移动文件到目标目录
        await file.mv(filePath);

        // 返回文件URL
        return {
            url: `/uploads/${fileName}`,
            fileName,
            originalName: file.name,
            size: file.size,
            mimetype: file.mimetype
        };
    } catch (error) {
        console.error('[UPLOAD] 文件上传失败:', error);
        throw new Error('文件上传失败');
    }
};

/**
 * 删除文件
 * @param {string} fileName 文件名
 * @returns {Promise<void>}
 */
const deleteFile = async (fileName) => {
    try {
        const filePath = path.join(uploadDir, fileName);
        if (fs.existsSync(filePath)) {
            await fs.promises.unlink(filePath);
        }
    } catch (error) {
        console.error('[UPLOAD] 文件删除失败:', error);
        throw new Error('文件删除失败');
    }
};

module.exports = {
    uploadFile,
    deleteFile
}; 